package com.dxy.dxyadmin.service.impl;

import com.dxy.dxyadmin.DO.Admin;
import com.dxy.dxyadmin.DO.Permission;
import com.dxy.dxyadmin.DO.Role;
import com.dxy.dxyadmin.DO.RolePermission;
import com.dxy.dxyadmin.DTO.PermissionTree;
import com.dxy.dxyadmin.VO.AdminVO;
import com.dxy.dxyadmin.enums.AdminEnum;
import com.dxy.dxyadmin.enums.ResultEnum;
import com.dxy.dxyadmin.exception.AdminException;
import com.dxy.dxyadmin.repository.*;
import com.dxy.dxyadmin.service.AdminService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * junfeng 2018/11/6
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private AdminRoleRepository adminRoleRepository;

    @Autowired
    private RolePermissionRepository rolePermissionRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    @Autowired
    private RoleRepository roleRepository;

    /**
     * 添加管理员
     *
     * @param adminVO
     * @return
     */
    @Override
    public Admin insertAdmin(AdminVO adminVO) {
        Admin admin = new Admin();
        if (!adminRepository.existsByName(adminVO.getName())) {
            BeanUtils.copyProperties(adminVO, admin);
            admin.setStatus(AdminEnum.NORMAL.getCode());
            adminRepository.save(admin);
        } else {
            admin = null;
        }
        return admin;
    }

    /**
     * 更新管理员信息
     *
     * @param adminVO
     * @return
     */
    @Override
    public Admin updateAdmin(AdminVO adminVO) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminVO, admin);
        try {
            adminRepository.save(admin);
        } catch (Exception e) {
            throw new AdminException(ResultEnum.ADMIN_DATABASE_FAIL);
        }
        return admin;
    }

    /**
     * 更新管理员状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public int updateStatusAdmin(Integer id, Integer status) {
        return adminRepository.updateStatusById(id, status);
    }

    @Override
    public Page<Admin> listAdmin(Integer page, Integer size, Map<String, Object> params) {
        Pageable pageable = new PageRequest(page, size);

        Specification specification = (Specification) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            String name;
            try {
                name = params.get("name").toString();
            } catch (Exception e) {
                name = null;
            }
            if (StringUtils.isNotBlank(name)) {
                predicates.add(cb.like(root.get("name"), "%" + name + "%"));
            }
            //todo 根据创建时间查找
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<Admin> adminInfos = adminRepository.findAll(specification, pageable);
        return adminInfos;
    }

    /**
     * 查询侧边栏
     *
     * @param name
     * @return
     */
    @Override
    public List<PermissionTree> querySide(String name) {
        List<Integer> pIdList = getPermisssionId(name);
        List<Permission> fList = new ArrayList<>();
        List<Permission> cList = new ArrayList<>();
        for (Integer p : pIdList) {
            Permission fPermission = permissionRepository.findByIdAndParentIdAndTitleIsNullAndCodeIsNull(p, 0);
            Permission cPermission = permissionRepository.findByIdAndTitleIsNullAndCodeIsNotNullAndUrlIsNotNull(p);
            if (fPermission != null) {
                fList.add(fPermission);
            }
            if (cPermission != null) {
                cList.add(cPermission);
            }
        }
        List<PermissionTree> permissionTreeList = new ArrayList<>();
        for (int i = 0; i < fList.size(); i++) {
            PermissionTree permissionTree = new PermissionTree();
            BeanUtils.copyProperties(fList.get(i), permissionTree);
            permissionTreeList.add(permissionTree);
        }
        for (int i = 0; i < permissionTreeList.size(); i++) {
            List<Permission> permissionList = new ArrayList<>();
            for (int j = 0; j < cList.size(); j++) {
                if (permissionTreeList.get(i).getId().equals(cList.get(j).getParentId())) {
                    Permission permission = cList.get(j);
                    permissionList.add(permission);
                }
            }
            permissionTreeList.get(i).setPermissionList(permissionList);
        }
        return permissionTreeList;
    }

    /**
     * 通过姓名 查询权限ID
     *
     * @param name
     * @return
     */
    @Override
    public Admin findByName(String name) {
        return adminRepository.findByName(name);
    }

    public List<Integer> getPermisssionId(String name) {
        Admin admin = adminRepository.findByNameAndStatus(name, AdminEnum.NORMAL.getCode());
        Integer id = admin.getId();
        if (id == null) {
            throw new AdminException(ResultEnum.NOT_IDENTITY_USER);
        }
        Integer roleId = adminRoleRepository.findByAdminId(id).getRoleId();
        List<RolePermission> rolePermission = rolePermissionRepository.findByRoleId(roleId);
        List<Integer> pIdList = rolePermission.stream().map(RolePermission::getPId).collect(Collectors.toList());
        return pIdList;
    }

    /**
     * 查询角色
     *
     * @param name
     * @return
     */
    @Override
    public Set<String> queryRoles(String name) {
        Set<String> roles = new HashSet<>();
        Integer adminId = adminRepository.findByName(name).getId();
        Integer roleId = adminRoleRepository.findByAdminId(adminId).getRoleId();
        Optional<Role> roleName = roleRepository.findById(roleId);
        Role rName = roleName.get();
        roles.add(rName.getName());
        return roles;
    }

    /**
     * 查询权限
     *
     * @param name
     * @return
     */
    @Override
    public Set<String> queryPermissions(String name) {
        Set<String> permissions = new HashSet<>();
        List<Integer> ids = getPermisssionId(name);
        List<Permission> trees = new ArrayList<>();
        for (Integer id : ids) {
            Permission permission = permissionRepository.findByIdAndCodeIsNotNull(id);
            if (permission != null) {
                trees.add(permission);
            }
        }
        for (Permission tree : trees) {
            String code = tree.getCode();
            if (!"".equals(code) && code != null) {
                permissions.add(code);
            }
        }
        return permissions;
    }

    @Override
    public List<Permission> queryBtn(String name, String title) {
        return permissionRepository.findByNameAndTitleIsNotNull(title);
    }


}
